package wbbs;

import cn.webwheel.DefaultMain;
import cn.webwheel.WebContext;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.ServletModule;
import org.apache.commons.dbutils.QueryRunner;
import org.h2.jdbcx.JdbcConnectionPool;
import wbbs.service.Utils;

import javax.sql.DataSource;

public class Main extends DefaultMain {

    private Injector injector;

    private JdbcConnectionPool pool;

    @Override
    protected void init() {

        //use mvel
        System.setProperty("webwheel.template.engine.mvel", "true");

        super.init();

        autoMap("wbbs.web");

        pool = JdbcConnectionPool.create("jdbc:h2:" + servletContext.getRealPath("/WEB-INF/h2") + ";LOCK_MODE=0", "sa", "");

        Utils.ensureDB(pool);

        injector = Guice.createInjector(createServletModule());
    }

    ServletModule createServletModule() {
        return new ServletModule() {
            @Override
            protected void configureServlets() {
                bind(DataSource.class).toInstance(pool);
                bind(QueryRunner.class).toInstance(new QueryRunner(pool));
            }
        };
    }

    @Override
    public <T> T createAction(WebContext ctx, Class<T> type) {
        return injector.getInstance(type);
    }

    @Override
    protected void destroy() {
        pool.dispose();
    }
}
